package com.yitao.cms.utils;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5EncryptionUtils {

    public static void main(String[] args) throws Exception {

        System.out.println(getMd5(getSha1("123456")));
    }


    public static String getSha1(String string) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return Encryption(string, "SHA1");
    }

    public static String getMd5(String str) throws Exception {
        return Encryption(str, "MD5");
    }


    /**
     * 加密函数  该方法会抛出异常
     *
     * @param str
     * @param encryptionType
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String Encryption(String str, String encryptionType) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (null == str || 0 == str.length()) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f'};

        MessageDigest mdTemp = MessageDigest.getInstance(encryptionType);
        mdTemp.update(str.getBytes("UTF-8"));

        byte[] md = mdTemp.digest();
        int j = md.length;
        char[] buf = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
            buf[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(buf);

    }
}
